﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneMap.Resources;
using System.Windows.Media.Animation;
using PhoneMap.Common;
using System.Windows.Media;
using System.Device.Location;
using Microsoft.Phone.Maps.Controls;
using Windows.Devices.Geolocation;
using PhoneMap.Controls;
using PhoneMap.ViewModel;
using System.Windows.Media.Imaging;

namespace PhoneMap
{
    public partial class MainPage : PhoneApplicationPage
    {
        private double dragDistanceToOpen = 75.0;
        private double dragDistanceToClose = 305.0;
        private double dragDistanceNegative = -75.0;

        private FrameworkElement feContainer;
        private bool isSettingsOpen = false;

        MapLayer PushpinMapLayer;
        private List<GeoCoordinate> listPostion;
        ProgressIndicator pi;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            feContainer = this.Container as FrameworkElement;
            listPostion = new List<GeoCoordinate>();
            Loaded += ViewPostion_Loaded;
            pi = new ProgressIndicator();
            pi.IsIndeterminate = true;
            pi.IsVisible = false;
           
        }
        private void CloseSettings()
        {
            var trans = feContainer.GetHorizontalOffset().Transform;
            trans.Animate(trans.X, 0, TranslateTransform.XProperty, 300, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            isSettingsOpen = false;
        }

        private void OpenSettings()
        {
            var trans = feContainer.GetHorizontalOffset().Transform;
            trans.Animate(trans.X, 380, TranslateTransform.XProperty, 300, 0, new CubicEase
            {
                EasingMode = EasingMode.EaseOut
            });

            isSettingsOpen = true;
        }
        private void GestureListener_OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange > 0 && !isSettingsOpen)
            {
                double offset = feContainer.GetHorizontalOffset().Value + e.HorizontalChange;
                if (offset > dragDistanceToOpen)
                    this.OpenSettings();
                else
                    feContainer.SetHorizontalOffset(offset);
            }

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange < 0 && isSettingsOpen)
            {
                double offsetContainer = feContainer.GetHorizontalOffset().Value + e.HorizontalChange;
                if (offsetContainer < dragDistanceToClose)
                    this.CloseSettings();
                else
                    feContainer.SetHorizontalOffset(offsetContainer);
            }
        }

        private void GestureListener_OnDragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange > 0 && !isSettingsOpen)
            {
                if (e.HorizontalChange < dragDistanceToOpen)
                    this.ResetLayoutRoot();
                else
                    this.OpenSettings();
            }

            if (e.Direction == System.Windows.Controls.Orientation.Horizontal && e.HorizontalChange < 0 && isSettingsOpen)
            {
                if (e.HorizontalChange > dragDistanceNegative)
                    this.ResetLayoutRoot();
                else
                    this.CloseSettings();
            }
        }

        private void ResetLayoutRoot()
        {
            if (!isSettingsOpen)
                feContainer.SetHorizontalOffset(0.0);
            else
                feContainer.SetHorizontalOffset(380.0);
        }
      

        async void ViewPostion_Loaded(object sender, RoutedEventArgs e)
        {
            ImageBrush image=new ImageBrush();
            image.ImageSource=new BitmapImage(new Uri(App.FacebookDatas.picture, UriKind.Absolute)){CreateOptions= BitmapCreateOptions.None};
            Avata.Source = image.ImageSource;
            UserName.Text = App.FacebookDatas.name;


            TextSearch.Visibility = System.Windows.Visibility.Collapsed;
            ShowName.Visibility = System.Windows.Visibility.Visible;
            await ShowPostion();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //Creating a MapLayer and adding the MapOverlay to it
            PushpinMapLayer = new MapLayer();
            MyMap.Layers.Add(PushpinMapLayer);

        }

        public  void ShowPostion(Geoposition posGeoposition)
        {
            MapOverlay MyOverlay = new MapOverlay();
            var showPost = new PushPinControl(App.FacebookDatas.picture, App.FacebookDatas.id);
            MyOverlay.Content = showPost;
            MyOverlay.GeoCoordinate = new GeoCoordinate(posGeoposition.Coordinate.Latitude, posGeoposition.Coordinate.Longitude); ;
            MyOverlay.PositionOrigin = new Point(0, 0.5);
            this.PushpinMapLayer.Add(MyOverlay);
            MyMap.Center = MyOverlay.GeoCoordinate;
            MyMap.ZoomLevel = 10;


        }
        private async System.Threading.Tasks.Task ShowPostion()
        {
            pi.IsVisible = true;
            pi.IsIndeterminate = true;
            pi.Text = "Resolving...";
            SystemTray.SetProgressIndicator(this, pi);
            this.Opacity = 0.5;
            //Getting Phone's current location
            Geolocator MyGeolocator = new Geolocator();
            MyGeolocator.DesiredAccuracyInMeters = 5;
            Geoposition myGeoPosition = null;
            try
            {
                myGeoPosition = await MyGeolocator.GetGeopositionAsync(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10));
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("Location is disabled in phone settings");
            }

            var getLocationMy = new GeoCoordinate(myGeoPosition.Coordinate.Latitude, myGeoPosition.Coordinate.Longitude);

            //Creating a MapOverlay and adding the Pushpin to it.
            MapOverlay MyOverlay = new MapOverlay();
            var showPost = new PushPinControl(App.FacebookDatas.picture,App.FacebookDatas.id);
            MyOverlay.Content = showPost;
            MyOverlay.GeoCoordinate = getLocationMy;
            MyOverlay.PositionOrigin = new Point(0, 0.5);

            // Add the MapOverlay containing the pushpin to the MapLayer
            this.PushpinMapLayer.Add(MyOverlay);
            // Set the center on the map
            foreach (var data in LoginViewModel.ListPostions)
            {
                var getLocation = new GeoCoordinate(data.latitude, data.longitude);
                //Creating a MapOverlay and adding the Pushpin to it.
                MapOverlay myPost = new MapOverlay();
                if(data.user_id!=null)
                    myPost.Content = new PushPinControl(string.Empty,data.user_id);
                myPost.GeoCoordinate = getLocation;
                myPost.PositionOrigin = new Point(0, 0.5);
                // Add the MapOverlay containing the pushpin to the MapLayer
                this.PushpinMapLayer.Add(myPost);
            }

            pi.IsVisible = false;
            pi.IsIndeterminate = false;
            pi.Text = "Complete";
            SystemTray.SetProgressIndicator(this, pi);
            this.Opacity = 1;

           
            MyMap.Center = getLocationMy;
            MyMap.ZoomLevel = 10;


        }

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            new  Exception();
        }

        private void mnuRoad_Click(object sender, EventArgs e)
        {
            MyMap.CartographicMode = MapCartographicMode.Road;
        }

        private void mnuAerial_Click(object sender, EventArgs e)
        {
            MyMap.CartographicMode = MapCartographicMode.Aerial;
        }

        private void mnuHybrid_Click(object sender, EventArgs e)
        {
            MyMap.CartographicMode = MapCartographicMode.Hybrid;
        }

        private void mnuTerrain_Click(object sender, EventArgs e)
        {
            MyMap.CartographicMode = MapCartographicMode.Terrain;
        }

        private void mnuLight_Click(object sender, EventArgs e)
        {
            MyMap.ColorMode = MapColorMode.Light;
        }

        private void mnuDark_Click(object sender, EventArgs e)
        {
            MyMap.ColorMode = MapColorMode.Dark;
        }


        private void StackPanel_Search(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TextSearch.Visibility = System.Windows.Visibility.Visible;
            ShowName.Visibility = System.Windows.Visibility.Collapsed;
            isSettingsOpen = false;
            ResetLayoutRoot();
        }

        private void btCancel(object sender, RoutedEventArgs e)
        {
            TextSearch.Visibility = System.Windows.Visibility.Collapsed;
            ShowName.Visibility = System.Windows.Visibility.Visible;
        }

        private void OpenMenu_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void OpenMenu_Open(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (isSettingsOpen)
                CloseSettings();
            else
                OpenSettings();
        }
    }
}